package com.qys.livesMall.common.thread;

import com.qys.livesMall.common.thread.holder.po.LoginUser;
import com.qys.livesMall.common.enums.LanguageEnum;
import org.springframework.stereotype.Component;

@Component
public class ThreadContext {

    /**
     * 保存用户对象的ThreadLocal
     */
    private static final ThreadLocal<LoginUser> userThreadLocal = new ThreadLocal<>();
    /**
     * 当前环境语言
     */
    public static LanguageEnum lang;


    /**
     * 添加当前登录用户方法
     */
    public static void addCurrentUser(LoginUser user){
        userThreadLocal.set(user);
    }

//    public static LoginUser getCurrentUser(){
//        return userThreadLocal.get();
//    }

    public static void setLang(String langStr){
        lang=LanguageEnum.getByLang(langStr);
    }


    /**
     * 防止内存泄漏
     */
    public static void remove(){
        userThreadLocal.remove();
    }

    public static LoginUser getUser(){
            return userThreadLocal.get();
    }

    public static Long getUserId(){
        LoginUser user=userThreadLocal.get();
        if (user==null){
            return null;
        }
        return user.getUserId();
    }

    public static String getUserName(){
        LoginUser user=userThreadLocal.get();
        if (user==null){
            return null;
        }
        return user.getUserName();
    }
}
